# Production Safe Update Script
# For bug fixes and minor updates
param(
    [switch]$SkipBackup,
    [switch]$SkipMigration,
    [switch]$DryRun,
    [string]$TargetCommit = "origin/main"
)

$ErrorActionPreference = "Stop"
$venvPath = "C:\VISION_HEALTH\.venv"
$projectPath = "C:\VISION_HEALTH"

function Write-StatusMessage {
    param($Message, $Color = "Cyan")
    Write-Host "[$(Get-Date -Format 'HH:mm:ss')] $Message" -ForegroundColor $Color
}

function Test-ServiceHealth {
    try {
        $response = Invoke-WebRequest -Uri "http://localhost:5000" -Method Get -TimeoutSec 5
        return $response.StatusCode -eq 200
    } catch {
        return $false
    }
}

function Get-GitChanges {
    $current = git rev-parse HEAD
    $target = git rev-parse $TargetCommit
    
    if ($current -eq $target) {
        return $false, "No updates needed, already up to date"
    }
    
    $changes = git log --oneline "${current}..${target}"
    return $true, $changes
}

try {
    Write-StatusMessage "=== Production Safe Update Started ===" "Green"
    
    # 1. Environment check
    Set-Location $projectPath
    Write-StatusMessage "Current directory: $(Get-Location)"
    
    # 2. Service health check
    if (Test-ServiceHealth) {
        Write-StatusMessage "Current service is running normally" "Green"
    } else {
        Write-StatusMessage "Current service is abnormal, please fix first" "Yellow"
        if (-not $DryRun) {
            $continue = Read-Host "Continue with update? (y/N)"
            if ($continue -ne "y") { exit 0 }
        }
    }
    
    # 3. Get update information
    git fetch origin
    $hasChanges, $changeInfo = Get-GitChanges
    
    if (-not $hasChanges) {
        Write-StatusMessage $changeInfo "Green"
        exit 0
    }
    
    Write-StatusMessage "Pending updates:"
    Write-Host $changeInfo -ForegroundColor Yellow
    
    if ($DryRun) {
        Write-StatusMessage "=== DRY RUN MODE - No actual updates performed ===" "Yellow"
        exit 0
    }
    
    # 4. User confirmation
    $confirm = Read-Host "Confirm update execution? (y/N)"
    if ($confirm -ne "y") {
        Write-StatusMessage "User cancelled update"
        exit 0
    }
    
    # 5. Create backup (optional)
    if (-not $SkipBackup) {
        $backupBranch = "backup-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
        git branch $backupBranch
        Write-StatusMessage "Created backup branch: $backupBranch"
    }
    
    # 6. Update code
    Write-StatusMessage "Updating code..."
    git pull origin main
    $newCommit = git rev-parse --short HEAD
    Write-StatusMessage "Updated to commit: $newCommit"
    
    # 7. Activate virtual environment
    Write-StatusMessage "Activating virtual environment..."
    if (Test-Path "$venvPath\Scripts\Activate.ps1") {
        & "$venvPath\Scripts\Activate.ps1"
    }
    
    # 8. Update dependencies (only if requirements.txt changed)
    $reqChanged = git diff --name-only HEAD~1 HEAD | Select-String "requirements"
    if ($reqChanged) {
        Write-StatusMessage "Requirements changed, updating dependencies..."
        pip install -r requirements.txt --upgrade
    } else {
        Write-StatusMessage "No dependency changes, skipping update"
    }
    
    # 9. Database migration (optional)
    if (-not $SkipMigration) {
        $migrationChanged = git diff --name-only HEAD~1 HEAD | Select-String "migrations"
        if ($migrationChanged) {
            Write-StatusMessage "Database migration detected, executing migration..."
            $env:FLASK_APP = "backend"
            flask db upgrade
        } else {
            Write-StatusMessage "No database migration needed, skipping"
        }
    }
    
    # 10. Graceful service restart
    Write-StatusMessage "Gracefully restarting service..."
    
    # Stop existing service
    Get-Process -Name "python" -ErrorAction SilentlyContinue | 
        Where-Object {$_.CommandLine -like "*waitress*" -or $_.CommandLine -like "*app.py*"} | 
        Stop-Process -Force
    
    Start-Sleep -Seconds 3
    
    # Start new service
    Start-Process -FilePath "powershell.exe" -ArgumentList "-File", ".\run_production_en.ps1" -WindowStyle Minimized
    Start-Sleep -Seconds 10
    
    # 11. Final verification
    if (Test-ServiceHealth) {
        Write-StatusMessage "=== Update completed successfully ===" "Green"
        Write-StatusMessage "New version commit: $newCommit" "Green"
        if (-not $SkipBackup) {
            Write-StatusMessage "Backup branch: $backupBranch" "Green"
        }
    } else {
        throw "Service health check failed"
    }
    
} catch {
    Write-StatusMessage "=== Update failed ===" "Red"
    Write-StatusMessage "Error: $($_.Exception.Message)" "Red"
    Write-StatusMessage "Please check manually and rollback if needed" "Red"
    exit 1
}
